import { ErrorType } from '../errors';
import { Controller } from 'egg';

export default function checkPermission(
  modelName: string,
  errorType: ErrorType,
  userKey = 'user',
): MethodDecorator {
  return function (_, __, descriptor: PropertyDescriptor) {
    const orginalMethod = descriptor.value;
    descriptor.value = async function (this: Controller, ...args: any) {
      const { ctx } = this;
      const { id } = ctx.params;
      // 获取当前用户的 ID
      const userId = ctx.state.user._id;
      // 查询作品信息
      const certianWork = await this.ctx.model[modelName].findOne({ id });
      if (!certianWork) {
        return false;
      }
      if (!certianWork || certianWork[userKey].toString() !== userId) {
        return ctx.helper.error({ ctx, errorType });
      }
      return orginalMethod.apply(this, args);
    };
  };
}
